import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Typography,
  Badge,
  Modal,
  message,
  Popconfirm,
  Tabs,
} from 'antd';
import {
  InboxOutlined,
  SendOutlined,
  EyeOutlined,
  DeleteOutlined,
  EditOutlined,
} from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { getInboxMessages, getOutboxMessages, markMessageRead, deleteMessage } from '../../api/message';
import { PrivateMessage, PageResult } from '../../types';
import { formatDateTime } from '../../utils/format';

const { Title, Text } = Typography;
const { TabPane } = Tabs;

const MessageInbox: React.FC = () => {
  const [messages, setMessages] = useState<PrivateMessage[]>([]);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('inbox');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const navigate = useNavigate();

  useEffect(() => {
    fetchMessages();
  }, [pagination.current, pagination.pageSize, activeTab]);

  const fetchMessages = async () => {
    try {
      setLoading(true);
      const apiCall = activeTab === 'inbox' ? getInboxMessages : getOutboxMessages;
      const response = await apiCall({
        page: pagination.current,
        size: pagination.pageSize,
      });

      if (response.code === 200) {
        setMessages(response.data.records);
        setPagination(prev => ({
          ...prev,
          total: response.data.total,
        }));
      }
    } catch (error) {
      console.error(`获取${activeTab === 'inbox' ? '收件箱' : '发件箱'}失败:`, error);
      message.error(`获取${activeTab === 'inbox' ? '收件箱' : '发件箱'}失败`);
    } finally {
      setLoading(false);
    }
  };

  const handleMarkRead = async (messageId: number) => {
    try {
      await markMessageRead(messageId);
      fetchMessages();
      message.success('已标记为已读');
    } catch (error) {
      console.error('标记已读失败:', error);
      message.error('标记已读失败');
    }
  };

  const handleDelete = async (messageId: number) => {
    try {
      await deleteMessage(messageId);
      fetchMessages();
      message.success('删除成功');
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  const handleTabChange = (key: string) => {
    setActiveTab(key);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  const getColumns = () => {
    const baseColumns = [
      {
        title: '状态',
        dataIndex: 'isRead',
        key: 'isRead',
        width: 60,
        render: (isRead: boolean) => (
          (activeTab === 'inbox' && !isRead) ? <Badge status="processing" /> : null
        ),
      },
      {
        title: activeTab === 'inbox' ? '发件人' : '收件人',
        dataIndex: activeTab === 'inbox' ? 'senderUsername' : 'receiverUsername',
        key: 'username',
        width: 120,
        render: (username: string, record: PrivateMessage) => (
          <Text strong={activeTab === 'inbox' && !record.isRead}>
            {username || (activeTab === 'inbox' ? record.fromUsername : record.receiverUsername)}
          </Text>
        ),
      },
      {
        title: '主题',
        dataIndex: 'subject',
        key: 'subject',
        render: (subject: string, record: PrivateMessage) => (
          <Link to={`/messages/${record.id}`}>
            <Text strong={activeTab === 'inbox' && !record.isRead}>
              {subject || record.title}
            </Text>
          </Link>
        ),
      },
      {
        title: '时间',
        dataIndex: 'createdTime',
        key: 'createdTime',
        width: 160,
        render: (time: string, record: PrivateMessage) => (
          <Text type="secondary">
            {formatDateTime(time || record.createdAt || '')}
          </Text>
        ),
      },
      {
        title: '操作',
        key: 'action',
        width: 160,
        render: (record: PrivateMessage) => (
          <Space>
            <Button
              type="text"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => navigate(`/messages/${record.id}`)}
            >
              查看
            </Button>
            {activeTab === 'inbox' && !record.isRead && (
              <Button
                type="text"
                size="small"
                onClick={() => handleMarkRead(record.id)}
              >
                标记已读
              </Button>
            )}
            {activeTab === 'inbox' && (
              <Button
                type="text"
                size="small"
                icon={<EditOutlined />}
                onClick={() => navigate(`/messages/compose?reply=${record.id}`)}
              >
                回复
              </Button>
            )}
            <Popconfirm
              title="确定要删除这条消息吗？"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="text"
                size="small"
                icon={<DeleteOutlined />}
                danger
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        ),
      },
    ];

    return baseColumns;
  };

  return (
    <div>
      <Card
        title={
          <Space>
            <InboxOutlined />
            <Title level={3} style={{ margin: 0 }}>私信</Title>
          </Space>
        }
        extra={
          <Link to="/messages/compose">
            <Button type="primary" icon={<EditOutlined />}>
              写私信
            </Button>
          </Link>
        }
      >
        <Tabs 
          activeKey={activeTab} 
          onChange={handleTabChange}
          items={[
            {
              key: 'inbox',
              label: (
                <span>
                  <InboxOutlined />
                  收件箱
                </span>
              ),
              children: (
                <Table
                  columns={getColumns()}
                  dataSource={messages}
                  rowKey="id"
                  loading={loading}
                  pagination={{
                    current: pagination.current,
                    pageSize: pagination.pageSize,
                    total: pagination.total,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total, range) => 
                      `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
                    onChange: (page, pageSize) => {
                      setPagination(prev => ({
                        ...prev,
                        current: page,
                        pageSize: pageSize || 20,
                      }));
                    },
                  }}
                  rowClassName={(record) => (activeTab === 'inbox' && record.isRead) ? '' : 'unread-message'}
                />
              )
            },
            {
              key: 'outbox',
              label: (
                <span>
                  <SendOutlined />
                  发件箱
                </span>
              ),
              children: (
                <Table
                  columns={getColumns()}
                  dataSource={messages}
                  rowKey="id"
                  loading={loading}
                  pagination={{
                    current: pagination.current,
                    pageSize: pagination.pageSize,
                    total: pagination.total,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total, range) => 
                      `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
                    onChange: (page, pageSize) => {
                      setPagination(prev => ({
                        ...prev,
                        current: page,
                        pageSize: pageSize || 20,
                      }));
                    },
                  }}
                />
              )
            }
          ]}
        />
      </Card>
    </div>
  );
};

export default MessageInbox; 